<template>
  <div class="box">
    <div class="login-containe">
      <h1>千峰管理系统</h1>
      <el-form
        :model="loginForm"
        status-icon
        :rules="rules"
        ref="loginForm"
        label-width="100px"
        class="login-loginForm"
      >
        <div v-if="!isErwei">
          <el-form-item label="用户名" prop="username">
            <el-input
              type="text"
              v-model="loginForm.username"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              v-model="loginForm.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="captcha">
            <el-input
              class="cap clear"
              v-model="loginForm.captcha"
              ref="cap"
              @keydown.native.enter="submitForm('loginForm')"
            ></el-input>
            <span @click="upCaptcha" class="vsg" v-html="svg"></span>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('loginForm')"
              >提交</el-button
            >
          </el-form-item>
        </div>
        <div class="erwei" v-else>
          <img :src="qrdataUrl" alt="" width="200px" height="200px" />
          <i
            :class="[
              'iconfont',
              isOk ? 'icon-saomachenggong' : 'icon-erweima_shixiao',
            ]"
            v-show="isSuccess"
          ></i>
          <p>微信扫码登录</p>
        </div>
      </el-form>
      <i
        @click="isErwei = !isErwei"
        :class="[
          'jiaobiao',
          'iconfont',
          isErwei ? 'icon-diannaojiaobiao' : 'icon-erweimajiaobiao',
        ]"
      ></i>
    </div>
    <div class="bg"></div>
    <video
      class="dv"
      muted="muted"
      src="http://chst.vip:8081/stu2/media/bg_video.d2d602a9.mp4"
      autoplay="autoplay"
      loop="loop"
      preload="auto"
    ></video>
  </div>
</template>

<script>
import * as api from "../../api/index";
import { mapMutations } from "vuex";
import io from "socket.io-client";
import qr from "qrcode";
var captcha = (rule, value, callback) => {
  if (value.length !== 5) {
    callback("验证码为五位");
  } else {
    callback();
  }
};
var validateusername = (rule, value, callback) => {
  let reg = /^\w{3,12}/;
  if (reg.test(value)) {
    callback();
  } else {
    callback("用户名必须为字母、数字或下划线，3到12位");
  }
};
var validatepassword = (rule, value, callback) => {
  if (value.length < 3) {
    callback("密码不得少于三位");
  } else {
    callback();
  }
};
export default {
  data() {
    return {
      isErwei: false,
      svg: "",
      loginForm: {
        username: "",
        password: "",
        captcha: "",
      },
      rules: {
        username: [{ validator: validateusername, trigger: "blur" }],
        password: [{ validator: validatepassword, trigger: "blur" }],
        captcha: [{ validator: captcha, trigger: "blur" }],
      },
      qrdataUrl: "",
      isSuccess: false,
      isOk: true,
    };
  },
  created() {
    this.upCaptcha();
  },
  methods: {
    getQrCode() {
      let sid = localStorage.getItem("qf-sid");
      if (!sid) {
        this.$message.error("没有sid");
        return;
      }
      api.getQrCodeUrl(sid).then((res) => {
        let qrUrl = res.data.scanCodeUrl;
        qr.toDataURL(qrUrl, (err, dataUrl) => {
          this.qrdataUrl = dataUrl;
        });
      });
    },
    ...mapMutations(["SET_USER_INFO", "GET_MENULIST"]),
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "正在登入...",
            spinner: "iconfont icon-jiazaizhong",
            background: "rgba(0, 0, 0, 0.7)",
          });
          api
            .verifyCaptcha(this.loginForm.captcha.toLowerCase())
            .then((res) => {
              if (res.data.state) {
                api
                  .loginApi(this.loginForm.username, this.loginForm.password)
                  .then((res) => {
                    if (res.data.state) {
                      loading.close();

                      this.$message.success({
                        message: "登入成功，正在跳转...",
                        type: "success",
                        duration: 1000,
                      });
                      localStorage.setItem("qf-token", res.data.token);
                      localStorage.setItem(
                        "qf-userInfo",
                        JSON.stringify(res.data.userInfo)
                      );
                      localStorage.setItem(
                        "permissionBtns",
                        JSON.stringify(res.data.permission.buttons)
                      );
                      this.SET_USER_INFO(res.data.userInfo);
                      this.$router.push("/");

                      //  this.$store.dispatch("GET_MENULIST");
                    } else {
                      loading.close();
                      this.$message.error("登入失败，用户名或密码错误");
                    }
                  });
              } else {
                loading.close();
                this.$message.error("验证码错误");
                this.loginForm.captcha = "";
                this.upCaptcha();
                this.$refs.cap.focus();
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    upCaptcha() {
      api.getCaptchaApi().then((res) => {
        this.svg = res.data.img;
      });
    },
  },
  watch: {
    isErwei(newVal, oldVal) {
      console.log(oldVal);
      if (newVal) {
        let socket = io("ws://chst.vip");
        socket.on("connectSuccess", (data) => {
          console.log("socket连接成功");
          let { sid } = data;
          localStorage.setItem("qf-sid", sid);
          this.getQrCode();
        });
        socket.on("scancodeSuccess", (data) => {
          // console.log("扫码成功")
          // console.log(data)
          if (data.state) {
            this.isSuccess = true;
            api.wechatLoginApi(data.wechatCode).then((res) => {
              // console.log(res);
              if (res.data.state) {
                localStorage.setItem("qf-token", res.data.token);
                localStorage.setItem(
                  "qf-userInfo",
                  JSON.stringify(res.data.userInfo)
                );
                localStorage.setItem(
                  "permissionBtns",
                  JSON.stringify(res.data.permission.buttons)
                );
                setTimeout(() => {
                  this.$router.push("/");
                }, 200);
              } else {
                this.$message.error("微信登入失败");
              }
            });
          } else {
            this.$message.error("扫码失败");
          }
        });
        socket.on("invalidCode", (data) => {
          console.log(data);
          this.isSuccess = true;
          this.isOk = false;
        });
      } else {
        this.isSuccess = false;
      }
    },
  },
};
</script>
<style scoped lang="less">
.box {
  width: 100%;
  height: 100%;
  position: relative;
  .bg {
    width: 50%;
    height: 100%;
    background-image: url(../../assets/images/bg2.png);
    background-repeat: no-repeat;
    background-size: 50%;
    position: fixed;
    opacity: 0.7;
    background-position: 60% 65%;
    z-index: 999;
  }
  .dv {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }
  .login-containe {
    width: 400px;
    height: 480px;
    position: absolute;
    top: 50%;
    left: 75%;
    transform: translate(-50%, 30%);
    border-radius: 11px;
    background: rgba(0, 0, 0, 0.2);
    text-align: center;
    z-index: 9;
    .el-form {
      position: relative;
      .cap {
        width: 40%;
        height: 44px;
        /deep/ input {
          // display: inline-block;
          border-top-left-radius: 5px;
          border-bottom-left-radius: 5px;
          border-top-right-radius: 0px;
          border-bottom-right-radius: 0px;
          border: 0;
          height: 44px;
        }
      }
      .vsg {
        width: 60%;
        display: inline-block;
        border-top-left-radius: 0px;
        border-bottom-left-radius: 0px;
        border-top-right-radius: 5px;
        border-bottom-right-radius: 5px;
        border: 0;
        background: #fff;
        height: 44px;
      }
    }
    .erwei {
      text-align: center;
      color: #fff;
      font-size: 25px;
      img {
        padding: 0 100px;
      }
      i {
        font-size: 200px;
        color: skyblue;
        display: inline-block;
        z-index: 999;
        position: absolute;
        top: -9px;
        left: 84px;
        opacity: 0.7;
      }
      .icon-erweima_shixiao {
        color: red !important;
        font-size: 250px;
        display: inline-block;
        z-index: 999;
        position: absolute;
        top: -37px;
        left: 76px;
        opacity: 0.5;
      }
      p {
        width: 400px;
        margin-top: 20px;
      }
    }
    h1 {
      color: rgb(255, 255, 255);
      margin-top: 100px;
      margin-bottom: 50px;
      font-size: 32px;
      font-family: "Miscrosoft yahei";
    }
    .jiaobiao {
      display: inline-block;
      width: 80px;
      height: 80px;
      font-size: 60px;
      position: absolute;
      right: -1px;
      top: -1px;
      color: #fff;
    }
    .el-button--primary {
      width: 250px;
    }

    .login-loginForm {
      width: 350px;
      padding-right: 50px;
      /deep/ .el-form-item__label {
        color: rgb(255, 255, 255);
        font-family: "Miscrosoft yahei";
      }
    }
  }
}
</style>
